package com.lin.services.impl;

import com.lin.dao.StoreDao;
import com.lin.dao.UserDao;
import com.lin.pojo.Store;
import com.lin.pojo.User;
import com.lin.services.StaffService;
import com.lin.utils.MD5Util;
import com.lin.utils.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ClassName:StaffServiceImpl
 * Package:com.lin.services.impl
 * Author: hellcat
 * Date: 2019/12/19
 * ♣♣♣
 */
@Service

public class StaffServiceImpl implements StaffService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private StoreDao storeDao;

    @Override
    public List<User> listStaffInfo(String searchName, String searchRoleId) {
        Integer storeId = ShiroUtil.getUser().getStoreId();
        return userDao.listStaffInfo(searchName, searchRoleId, storeId);
    }

    @Override
    public List<Map<String, Object>> listRoles() {
        return userDao.listRoles(ShiroUtil.getUser().getStoreId());
    }

    @Override
    public Map<String, Object> getUserRoleById(String id) {
        List<Map<String, Object>> list = userDao.listRoles(ShiroUtil.getUser().getStoreId());
        List<String> userRoleList = userDao.getUserRoleList(Integer.parseInt(id), ShiroUtil.getUser().getStoreId());
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", true);
        resultMap.put("msg", "success");
        for (Map<String, Object> map : list) {
            map.put("value", map.get("id"));
            map.put("name", map.get("role"));
            for (String s : userRoleList) {
                if (s.equals(map.get("role"))) {
                    map.put("selected", true);
                    break;
                } else {
                    map.put("selected", false);
                }
            }
            map.put("disabled", false);
            map.remove("id");
            map.remove("role");
            mapList.add(map);
        }
        resultMap.put("data", mapList);
        return resultMap;
    }

    @Override
    public Map<String, Object> updateStuff(Map<String, String[]> parameterMap) {
        Map<String, Object> map = new HashMap<>();
        try {
            String id = parameterMap.get("id")[0].trim();
            Store store = storeDao.getStoreInfoById(ShiroUtil.getUser().getStoreId());
            if (store.getContactsId() == Integer.parseInt(id) && !store.getContactsId().equals(ShiroUtil.getUserId())) {
                map.put("code", false);
                map.put("msg", "当前用户不可修改");
                return map;
            }
            Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
            Matcher m = p.matcher(parameterMap.get("phone")[0].trim());
            if (!m.matches()) {
                map.put("msg", "手机号不规范");
                return map;
            }
            if (parameterMap.containsKey("pwd") && !"".equals(parameterMap.get("pwd")[0].trim())) {
                Pattern p2 = Pattern.compile("^(?=.*\\d)(?=.*[A-Za-z])[\\x21-\\x7e]{4,16}$");
                Matcher m2 = p2.matcher(parameterMap.get("pwd")[0].trim());
                if (!m2.matches()) {
                    map.put("msg", "密码不规范");
                    return map;
                }
            }
            if ("".equals(parameterMap.get("name")[0].trim())) {
                map.put("msg", "姓名不规范");
                return map;
            }
            User user = new User();
            user.setId(Integer.parseInt(parameterMap.get("id")[0].trim()));
            user.setName(parameterMap.get("name")[0].trim());
            user.setAccountNumber(parameterMap.get("accountNumber")[0].trim());
            if (parameterMap.containsKey("pwd") && !"".equals(parameterMap.get("pwd")[0].trim())) {
                user.setPwd(MD5Util.encrypted(user.getAccountNumber(), parameterMap.get("pwd")[0].trim()));
            }
            user.setPhone(parameterMap.get("phone")[0].trim());
            user.setSex(parameterMap.get("sex")[0].trim());
            user.setStoreId(ShiroUtil.getUser().getStoreId());
            String[] roles = parameterMap.get("select")[0].trim().split(",");
            User userByUsername = userDao.getUserByUsername(user.getAccountNumber());
            if (userByUsername != null && !userByUsername.getId().toString().equals(parameterMap.get("id")[0].trim())) {
                map.put("code", false);
                map.put("msg", "账号已存在");
                return map;
            }
            int i = userDao.updateUser(user);
            if (i == 1) {
                userDao.deleteUserRoleByUserId(user.getId());
                if (!"".equals(roles[0].trim())) {
                    for (String roleId : roles) {
                        userDao.insertUserRole(user.getId(), roleId);
                    }
                }
                ShiroUtil.clearAllCachedInfo(user.getAccountNumber());
                map.put("code", true);
            }
        } catch (Exception e) {
            map.clear();
            map.put("code", false);
            map.put("msg", "修改失败，未知异常");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return map;
    }

    @Override
    public Map<String, Object> deleteStuff(String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", false);
        map.put("msg", "删除失败");
        if (id != null && !"".equals(id.trim())) {
            try {
                Store store = storeDao.getStoreInfoById(ShiroUtil.getUser().getStoreId());
                if (store.getContactsId().equals(Integer.parseInt(id))) {
                    map.put("msg", "该用户不可删除");
                    return map;
                }
                User userById = userDao.getUserById(Integer.parseInt(id));
                ShiroUtil.clearAllCachedInfo(userById.getAccountNumber());
                int i = userDao.deleteStuff(id, ShiroUtil.getUser().getStoreId());
                if (i == 1) {
                    map.put("code", true);
                }
            } catch (Exception e) {
                map.clear();
                map.put("code", false);
                map.put("msg", "未知错误，稍后再试");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> updateAccountStatus(String id, String status) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", false);
        map.put("msg", "更新失败");
        if (id != null && !"".equals(id.trim()) && status != null && !"".equals(status.trim())) {
            Store store = storeDao.getStoreInfoById(ShiroUtil.getUser().getStoreId());
            if (store.getContactsId() == Integer.parseInt(id)) {
                map.put("code", false);
                map.put("msg", "当前用户不可修改");
                return map;
            }
            int i = userDao.updateAccountStatus(id, status, ShiroUtil.getUser().getStoreId());
            if (i == 1) {
                map.put("code", true);
                try {
                    User userById = userDao.getUserById(Integer.parseInt(id));
                    ShiroUtil.clearAllCachedInfo(userById.getAccountNumber());
                } catch (Exception e) {
                    map.clear();
                    map.put("code", false);
                    map.put("msg", "修改失败，未知异常");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> insertStaff(Map<String, String[]> parameterMap) {
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "创建失败");
        map.put("code", false);
        String regex = "^[a-z0-9A-Z]+$";
        if (!parameterMap.get("accountNumber")[0].trim().matches(regex)) {
            map.put("msg", "账号只能为数字/字母");
            return map;
        }
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(parameterMap.get("phone")[0].trim());
        if (!m.matches()) {
            map.put("msg", "手机号不规范");
            return map;
        }
        Pattern p2 = Pattern.compile("^(?=.*\\d)(?=.*[A-Za-z])[\\x21-\\x7e]{4,16}$");
        Matcher m2 = p2.matcher(parameterMap.get("pwd")[0].trim());
        if (!m2.matches()) {
            map.put("msg", "密码不规范");
            return map;
        }
        if ("".equals(parameterMap.get("name")[0].trim())) {
            map.put("msg", "姓名不规范");
            return map;
        }
        User user = new User();
        user.setStoreId(ShiroUtil.getUser().getStoreId());
        user.setName(parameterMap.get("name")[0].trim());
        user.setAccountNumber(parameterMap.get("accountNumber")[0].trim());
        user.setPwd(MD5Util.encrypted(user.getAccountNumber(), parameterMap.get("pwd")[0].trim()));
        if (parameterMap.containsKey("sex")) {
            user.setSex(parameterMap.get("sex")[0].trim());
        }
        user.setPhone(parameterMap.get("phone")[0].trim());
        user.setStoreId(ShiroUtil.getUser().getStoreId());
        String[] roles = parameterMap.get("select")[0].trim().split(",");
        User userByUsername = userDao.getUserByUsername(user.getAccountNumber());
        if (userByUsername != null) {
            map.put("msg", "账号已存在,请重新输入");
            return map;
        }
        userDao.insertStaff(user);
        Integer userId = user.getId();
        if (userId != null) {
            if (!"".equals(roles[0].trim())) {
                for (String role : roles) {
                    userDao.insertUserRole(userId, role);
                }
            }
            map.put("code", true);
            map.put("msg", "创建成功");
        }
        return map;
    }

}
